package com.pingao.mp.modular.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pingao.mp.modular.sys.entity.Permission;
import com.pingao.mp.modular.sys.entity.Role;
import com.pingao.mp.modular.sys.service.PermissionService;
import com.pingao.mp.utils.Constant;
import com.pingao.mp.utils.set.MapBuilder;
import com.pingao.mp.modular.sys.service.MenuService;
import com.pingao.mp.modular.sys.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author 闻品高
 * @since 2018-09-26
 */
@RestController
@RequestMapping("/sys/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @Autowired
    private MenuService menuService;

    @GetMapping("/list")
    @ResponseBody
    public Object list(@RequestParam("pageNumber") Integer pageNumber,
                       @RequestParam("pageSize") Integer pageSize,
                       @RequestParam("searchText") String searchText,
                       @RequestParam("sortName") String sortName,
                       @RequestParam("sortOrder") String sortOrder,
                       @RequestParam(value = "name", required = false) String name,
                       @RequestParam(value = "code", required = false) String code
    ) {
        return roleService.getRoleList(pageNumber, pageSize, searchText, sortName, sortOrder, name, code);
    }

    @PostMapping("/add")
    public Object add(Role role) {
        Map<String, Object> map = new HashMap<>();
        //判断角色code是否已经存在
        if (roleService.getOne(new QueryWrapper<Role>().eq(Role.COL_CODE, role.getCode()).isNull(Role.COL_DELETE_TIME)) != null) {
            map.put("status", false);
            map.put("msg", "角色code已经存在，请填写不存在的code");
            return map;
        }
        role.setUserId(1L);
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        if (!roleService.save(role)) {
            map.put("status", false);
            map.put("msg", "保存角色出错......");
            return map;
        }
        map.put("status", true);
        map.put("msg", "保存角色成功");
        map.put("role", role);
        return map;
    }

    @DeleteMapping("/delete")
    public Object delete(
            @RequestParam(value = "ids") String ids
    ) {
        String[] split = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        for (String id : split) {
            if (id.equals("1")) {
                continue;//不能删除admin角色
            }
            //删除权限表中关于该角色的信息
            permissionService.remove(new QueryWrapper<Permission>().eq(Permission.COL_ROLE_ID, id));
            roleService.deleteRoleById(Long.parseLong(id));
        }
        map.put("status", true);
        map.put("msg", "删除成功");
        map.put("ids", ids);
        return map;
    }

    @GetMapping("/get")
    public Object edit(@RequestParam("id") Long id) {
        MapBuilder<String, Object> m = new MapBuilder<>();
        Role role = roleService.getById(id);
        if (role == null) {
            throw new NullPointerException("该角色不存在--this role is not exits!!!");
        }
        m.put(Constant.ApiStatus, true).put(Constant.ApiData, role).put(Constant.ApiMsg, "获取成功");
        return m.get();
    }

    @PostMapping("/edit")
    @ResponseBody
    public Object edit(Role role) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //判断code是否在其他 role里存在
        if (roleService.getOne(new QueryWrapper<Role>().eq(Role.COL_CODE, role.getCode()).isNull(Role.COL_DELETE_TIME).notIn(Role.COL_ID, role.getId())) != null) {
            map.put("status", false);
            map.put("msg", "角色code已经存在，请填写不存在的code");
            return map;
        }

        role.setUserId(1L);
        role.setUpdateTime(LocalDateTime.now());
        roleService.updateById(role);
        map.put("status", true);
        map.put("msg", "保存角色成功");
        map.put("role", role);
        return map;
    }

    @GetMapping("/roleSetting")
    public Object role(@RequestParam("id") Long id) {
        MapBuilder<String, Object> m = new MapBuilder<>();
        Role role = roleService.getById(id);
        if (role == null) {
            throw new NullPointerException("该角色不存在--this role is not exits!!!");
        }
        Map<String, Object> data = roleService.getMenuList(id);
        m.put(Constant.ApiStatus, true).put(Constant.ApiMsg, "获取成功").put("role", role).put(Constant.ApiData, data);
        return m.get();
    }

    @GetMapping("/menu/{id}")
    public Object menu(@PathVariable("id") Long id) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> menus = roleService.getMenuList(id);
        map.put("rows", menus);
        return map;
    }

    @PostMapping("/roleSetting")
    public Object role(@RequestParam("id") Long id, @RequestParam("menuIds") String menuIds) {
        Role role = roleService.getById(id);
        if (role == null) {
            throw new NullPointerException("该角色不存在--this role is not exits!!!");
        }
        Map<String, Object> map = new HashMap<>();
        String[] split = menuIds.split(",");
        List<Long> ms = new ArrayList<>();
        for (String s : split) {
            ms.add(Long.parseLong(s));
        }
        roleService.savePermissions(id, ms);
        map.put("status", true);
        map.put("msg", "权限设置成功");
        map.put("role", role);
        map.put("menuIds", menuIds);
        return map;
    }
}
